<template>
  <div class="direction-charts">
    <el-row :gutter="20">
      <el-col :span="12">
        <div ref="courseChartRef" class="chart-container"></div>
      </el-col>

      <el-col :span="12">
        <div ref="timeChartRef" class="chart-container"></div>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt20">
      <el-col :span="12">
        <div ref="competitionChartRef" class="chart-container"></div>
      </el-col>

      <el-col :span="12">
        <div ref="projectChartRef" class="chart-container"></div>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt20">
      <el-col :span="12">
        <div ref="innovationChartRef" class="chart-container"></div>
      </el-col>

      <el-col :span="12">
        <el-table :data="directionStats" style="width: 100%" border>
          <el-table-column prop="directionName" label="方向名称" align="center" />
          <el-table-column prop="studentCount" label="学生人数" align="center" />
          <el-table-column prop="courseScore" label="课程学习总分" align="center" />
          <el-table-column prop="timeScore" label="学习时长总分" align="center">
            <template #default="scope">
              {{ formatMinutesToHours(scope.row.timeScore) }}
            </template>
          </el-table-column>
          <el-table-column prop="competitionScore" label="竞赛情况总分" align="center" />
          <el-table-column prop="projectScore" label="项目实践总分" align="center" />
          <el-table-column prop="innovationScore" label="科创贡献总分" align="center" />
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import { listStudent } from "@/api/infomanagement/student";
import { listLog } from "@/api/analyzemanagement/log";

// 定义props
const props = defineProps({
  logList: {
    type: Array,
    default: () => [],
  },
  directionList: {
    type: Array,
    default: () => [],
  },
});

// 图表实例
const courseChartRef = ref(null);
const timeChartRef = ref(null);
const competitionChartRef = ref(null);
const projectChartRef = ref(null);
const innovationChartRef = ref(null);
let courseChartInstance = null;
let timeChartInstance = null;
let competitionChartInstance = null;
let projectChartInstance = null;
let innovationChartInstance = null;

// 方向统计数据
const directionStats = ref([]);

// 学生数据
const studentData = ref([]);

// 日志数据
const logData = ref([]);

// 将分钟数转换为"X小时Y分钟"格式
const formatMinutesToHours = (minutes) => {
  if (!minutes && minutes !== 0) return "0分钟";

  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;

  if (hours > 0 && mins > 0) {
    return `${hours}小时${mins}分钟`;
  } else if (hours > 0) {
    return `${hours}小时`;
  } else {
    return `${mins}分钟`;
  }
};

// 获取学生数据
const fetchStudentData = async () => {
  try {
    // 获取所有学生数据
    const res = await listStudent({});
    if (res.code === 200) {
      studentData.value = res.rows || [];
    }
  } catch (error) {
    console.error("获取学生数据失败:", error);
  }
};

// 获取日志数据
const fetchLogData = async () => {
  try {
    // 获取所有日志数据
    const res = await listLog({});
    if (res.code === 200) {
      logData.value = res.rows || [];
    }
  } catch (error) {
    console.error("获取日志数据失败:", error);
  }
};

// 计算方向统计数据
const calculateDirectionStats = () => {
  // 初始化统计数据结构
  // 第一层：按direction字段对数据进行方向维度的区分
  const statsByDirection = {};

  // 初始化每个方向的数据结构
  props.directionList.forEach((direction) => {
    statsByDirection[direction.id] = {
      directionId: direction.id,
      directionName: direction.directionName,
      studentCount: 0,
      students: new Set(), // 使用Set来统计不重复的学生
      // 第二层：在每个方向下，按logType字段区分不同的分析维度
      scoresByLogType: {
        0: 0, // 课程学习
        1: 0, // 学习时长
        2: 0, // 竞赛情况
        3: 0, // 项目实践
        4: 0, // 科创贡献
      },
    };
  });

  // 根据学生数据统计各方向学生人数
  studentData.value.forEach((student) => {
    if (!student.directionId) return;

    if (!statsByDirection[student.directionId]) {
      // 如果方向不在列表中，跳过
      return;
    }

    // 添加学生到Set中
    const studentKey = `${student.studentNumber}-${student.studentName}`;
    statsByDirection[student.directionId].students.add(studentKey);
  });

  // 处理日志数据
  logData.value.forEach((log) => {
    // 检查日志数据是否包含必要的字段
    if (
      !log.direction ||
      log.logType === undefined ||
      log.logType === null ||
      log.score === undefined ||
      log.score === null
    ) {
      return;
    }

    // 检查方向是否存在于统计数据中
    if (!statsByDirection[log.direction]) {
      // 如果方向不在列表中，跳过
      return;
    }

    // 第三层：对每个方向下各分析维度对应的score值进行求和
    const scoreValue = parseFloat(log.score) || 0;
    statsByDirection[log.direction].scoresByLogType[log.logType] += scoreValue;
  });

  // 转换为数组并按方向ID排序
  const sortedDirections = Object.values(statsByDirection).sort(
    (a, b) => a.directionId - b.directionId
  );

  // 计算学生人数和总分，并转换为表格所需格式
  const result = sortedDirections.map((item) => {
    const studentCount = item.students.size;
    const courseScore = item.scoresByLogType[0];
    const timeScore = item.scoresByLogType[1];
    const competitionScore = item.scoresByLogType[2];
    const projectScore = item.scoresByLogType[3];
    const innovationScore = item.scoresByLogType[4];
    const totalScore =
      courseScore + timeScore + competitionScore + projectScore + innovationScore;

    return {
      directionId: item.directionId,
      directionName: item.directionName,
      studentCount,
      courseScore,
      timeScore,
      competitionScore,
      projectScore,
      innovationScore,
      totalScore,
    };
  });

  directionStats.value = result;
  return result;
};

// 初始化课程学习图表
const initCourseChart = () => {
  if (courseChartRef.value) {
    courseChartInstance = echarts.init(courseChartRef.value);
    updateCourseChart();
  }
};

// 更新课程学习图表
const updateCourseChart = () => {
  if (!courseChartInstance) return;

  const barChartData = getBarChartDataFromLogData();

  const option = {
    title: {
      text: "各方向课程学习得分对比",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: barChartData.directionNames,
      axisLabel: {
        interval: 0,
        rotate: 0,
      },
    },
    yAxis: {
      type: "value",
      name: "得分",
    },
    series: [
      {
        name: "课程学习得分",
        type: "bar",
        data: barChartData.courseScores,
        itemStyle: {
          color: "#5470c6",
        },
      },
    ],
  };

  courseChartInstance.setOption(option, true);
};

// 初始化学习时长图表
const initTimeChart = () => {
  if (timeChartRef.value) {
    timeChartInstance = echarts.init(timeChartRef.value);
    updateTimeChart();
  }
};

// 更新学习时长图表
const updateTimeChart = () => {
  if (!timeChartInstance) return;

  const barChartData = getBarChartDataFromLogData();

  const option = {
    title: {
      text: "各方向学习时长对比",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      formatter: function (params) {
        const value = params[0].value;
        return `${params[0].name}<br/>${params[0].seriesName}: ${formatMinutesToHours(
          value
        )}`;
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: barChartData.directionNames,
      axisLabel: {
        interval: 0,
        rotate: 0,
      },
    },
    yAxis: {
      type: "value",
      name: "分钟",
    },
    series: [
      {
        name: "学习时长",
        type: "bar",
        data: barChartData.timeScores,
        itemStyle: {
          color: "#91cc75",
        },
      },
    ],
  };

  timeChartInstance.setOption(option, true);
};

// 初始化竞赛情况图表
const initCompetitionChart = () => {
  if (competitionChartRef.value) {
    competitionChartInstance = echarts.init(competitionChartRef.value);
    updateCompetitionChart();
  }
};

// 更新竞赛情况图表
const updateCompetitionChart = () => {
  if (!competitionChartInstance) return;

  const barChartData = getBarChartDataFromLogData();

  const option = {
    title: {
      text: "各方向竞赛情况得分对比",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: barChartData.directionNames,
      axisLabel: {
        interval: 0,
        rotate: 0,
      },
    },
    yAxis: {
      type: "value",
      name: "得分",
    },
    series: [
      {
        name: "竞赛情况得分",
        type: "bar",
        data: barChartData.competitionScores,
        itemStyle: {
          color: "#fac858",
        },
      },
    ],
  };

  competitionChartInstance.setOption(option, true);
};

// 初始化项目实践图表
const initProjectChart = () => {
  if (projectChartRef.value) {
    projectChartInstance = echarts.init(projectChartRef.value);
    updateProjectChart();
  }
};

// 更新项目实践图表
const updateProjectChart = () => {
  if (!projectChartInstance) return;

  const barChartData = getBarChartDataFromLogData();

  const option = {
    title: {
      text: "各方向项目实践得分对比",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: barChartData.directionNames,
      axisLabel: {
        interval: 0,
        rotate: 0,
      },
    },
    yAxis: {
      type: "value",
      name: "得分",
    },
    series: [
      {
        name: "项目实践得分",
        type: "bar",
        data: barChartData.projectScores,
        itemStyle: {
          color: "#ee6666",
        },
      },
    ],
  };

  projectChartInstance.setOption(option, true);
};

// 初始化科创贡献图表
const initInnovationChart = () => {
  if (innovationChartRef.value) {
    innovationChartInstance = echarts.init(innovationChartRef.value);
    updateInnovationChart();
  }
};

// 更新科创贡献图表
const updateInnovationChart = () => {
  if (!innovationChartInstance) return;

  const barChartData = getBarChartDataFromLogData();

  const option = {
    title: {
      text: "各方向科创贡献得分对比",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: barChartData.directionNames,
      axisLabel: {
        interval: 0,
        rotate: 0,
      },
    },
    yAxis: {
      type: "value",
      name: "得分",
    },
    series: [
      {
        name: "科创贡献得分",
        type: "bar",
        data: barChartData.innovationScores,
        itemStyle: {
          color: "#73c0de",
        },
      },
    ],
  };

  innovationChartInstance.setOption(option, true);
};

// 调整图表大小
const resizeChart = () => {
  if (courseChartInstance) {
    courseChartInstance.resize();
  }
  if (timeChartInstance) {
    timeChartInstance.resize();
  }
  if (competitionChartInstance) {
    competitionChartInstance.resize();
  }
  if (projectChartInstance) {
    projectChartInstance.resize();
  }
  if (innovationChartInstance) {
    innovationChartInstance.resize();
  }
};

// 从logData直接获取柱状图数据
const getBarChartDataFromLogData = () => {
  // 初始化统计数据结构
  // 第一层：按direction字段对数据进行方向维度的区分
  const statsByDirection = {};

  // 初始化每个方向的数据结构
  props.directionList.forEach((direction) => {
    statsByDirection[direction.id] = {
      directionId: direction.id,
      directionName: direction.directionName,
      // 第二层：在每个方向下，按logType字段区分不同的分析维度
      scoresByLogType: {
        0: 0, // 课程学习
        1: 0, // 学习时长
        2: 0, // 竞赛情况
        3: 0, // 项目实践
        4: 0, // 科创贡献
      },
    };
  });

  // 处理日志数据
  logData.value.forEach((log) => {
    // 检查日志数据是否包含必要的字段
    if (
      !log.direction ||
      log.logType === undefined ||
      log.logType === null ||
      log.score === undefined ||
      log.score === null
    ) {
      return;
    }

    // 检查方向是否存在于统计数据中
    if (!statsByDirection[log.direction]) {
      // 如果方向不在列表中，跳过
      return;
    }

    // 第三层：对每个方向下各分析维度对应的score值进行求和
    const scoreValue = parseFloat(log.score) || 0;
    statsByDirection[log.direction].scoresByLogType[log.logType] += scoreValue;
  });

  // 转换为数组并按方向ID排序
  const sortedDirections = Object.values(statsByDirection).sort(
    (a, b) => a.directionId - b.directionId
  );

  // 准备柱状图数据
  const directionNames = sortedDirections.map((item) => item.directionName);
  const courseScores = sortedDirections.map((item) => item.scoresByLogType[0]);
  const timeScores = sortedDirections.map((item) => item.scoresByLogType[1]);
  const competitionScores = sortedDirections.map((item) => item.scoresByLogType[2]);
  const projectScores = sortedDirections.map((item) => item.scoresByLogType[3]);
  const innovationScores = sortedDirections.map((item) => item.scoresByLogType[4]);

  return {
    directionNames,
    courseScores,
    timeScores,
    competitionScores,
    projectScores,
    innovationScores,
  };
};

// 暴露方法给父组件
defineExpose({
  resizeChart,
});

// 组件挂载时初始化
onMounted(async () => {
  await fetchStudentData();
  await fetchLogData();
  calculateDirectionStats();
  initCourseChart();
  initTimeChart();
  initCompetitionChart();
  initProjectChart();
  initInnovationChart();
  window.addEventListener("resize", resizeChart);
});

// 监听数据变化，更新图表
watch(
  () => [props.directionList, studentData.value, logData.value],
  async () => {
    // 如果学生数据为空，重新获取
    if (studentData.value.length === 0) {
      await fetchStudentData();
    }
    // 如果日志数据为空，重新获取
    if (logData.value.length === 0) {
      await fetchLogData();
    }
    nextTick(() => {
      calculateDirectionStats();
      updateCourseChart();
      updateTimeChart();
      updateCompetitionChart();
      updateProjectChart();
      updateInnovationChart();
    });
  },
  { deep: true }
);
</script>

<style scoped>
.direction-charts {
  width: 100%;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.mt20 {
  margin-top: 20px;
}
</style>